package com.junson.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.junson.client.EchoClient;
import com.junson.client.handler.NettyHeartBeatDuplexHandler;
import com.junson.server.codec.Decoder;
import com.junson.server.codec.Encoder;
import com.junson.server.handler.EchoServerHandler;


/**
 * 代码清单 2-2 EchoServer 类
 *
 * @author <a href="mailto:norman.maurer@gmail.com">Norman Maurer</a>
 */
public class EchoServer {
	private static Logger logger = LoggerFactory.getLogger(EchoServer.class);
    private final int port;
    private static final int DEFAULT_THREAD_NUM = Runtime.getRuntime().availableProcessors() * 2;
    
    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args)
        throws Exception {
        if (args.length != 1) {
        	logger.debug("Usage: " + EchoServer.class.getSimpleName() +" <port>");
            return;
        }
        //设置端口值（如果端口参数的格式不正确，则抛出一个NumberFormatException）
        int port = Integer.parseInt(args[0]);
        logger.debug("Usage: " + EchoServer.class.getSimpleName() +" <"+ port +">");
        //调用服务器的 start()方法
        new EchoServer(port).start();
    }

    public void start() throws Exception {
        //(1) 创建EventLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
        	EventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(DEFAULT_THREAD_NUM);
            //(2) 创建ServerBootstrap
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group, workerGroup)
                //(3) 指定所使用的 NIO 传输 Channel
                .channel(NioServerSocketChannel.class)
                //(4) 使用指定的端口设置套接字地址
                //(5) 添加一个EchoServerHandler到于Channel的 ChannelPipeline
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //EchoServerHandler 被标注为@Shareable，所以我们可以总是使用同样的实例
                        //这里对于所有的客户端连接来说，都会使用同一个 EchoServerHandler，因为其被标注为@Sharable，
                        //这将在后面的章节中讲到。
                    	ch.pipeline().addLast(new IdleStateHandler(60, 20, 0, TimeUnit.SECONDS));
                    	ch.pipeline().addLast(new Encoder(CharsetUtil.UTF_8));
                        ch.pipeline().addLast(new Decoder(CharsetUtil.UTF_8));
                        ch.pipeline().addLast(new NettyHeartBeatDuplexHandler());
                        ch.pipeline().addLast(eventExecutorGroup, new EchoServerHandler());
                    }
                });
            //(6) 异步地绑定服务器；调用 sync()方法阻塞等待直到绑定完成
          //通过配置好的 ServerBootstrap 的实例绑定该 Channel
            ChannelFuture future = bootstrap.bind(new InetSocketAddress(port)).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture)
                    throws Exception {
                    if (channelFuture.isSuccess()) {
                    	logger.debug("Server bound");
                    } else {
                    	logger.debug("Bind attempt failed");
                        channelFuture.cause().printStackTrace();
                    }
                }
            });
            future.channel().closeFuture().sync();
        } finally {
            //(8) 关闭 EventLoopGroup，释放所有的资源
            group.shutdownGracefully().sync();
            workerGroup.shutdownGracefully();
        }
    }
}
